package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.BizType;
import com.bestv.search.common.model.SysUser;
import com.bestv.search.common.service.BizTypeManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BizTypeCommand {

    protected final Log log = LogFactory.getLog(getClass());
    private BizTypeManager bizTypeManager;

    public BizTypeManager getBizTypeManager() {
        return bizTypeManager;
    }

    public void setBizTypeManager(BizTypeManager bizTypeManager) {
        this.bizTypeManager = bizTypeManager;
    }

    public String findBizTypes(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        String result = "";
        List<BizType> bts = bizTypeManager.getAllBizTypes(dsKey);
        try {
            JSONArray array = bizTypesToJson(bts);
            result = "{'p_types' : " + array.toString() + "}";
        } catch (JSONException e) {
            log.error(e);
        }
        return result;
    }

    private JSONArray bizTypesToJson(List<BizType> bts) throws JSONException {
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (BizType t : bts) {
            list.add(bizTypeTOJSON(t));
        }
        JSONArray jsonArray = new JSONArray(list.toArray());
        return jsonArray;
    }

    private JSONObject bizTypeTOJSON(BizType bt) throws JSONException {
        JSONObject jo = new JSONObject();
        jo.put("id", String.valueOf(bt.getId()));
        jo.put("name", bt.getPtype());
        return jo;
    }
}
